import platform
import sys
from threading import Thread

from PyQt5 import QtWidgets, QtCore
from PyQt5.QtCore import pyqtSignal, QObject

from EChatIMSDKBridge import echatimSdk
from ui.dialog import Ui_Dialog

TEST_APIS_DICT = [
    {"给IM用户发送消息": ("sendMessage", "{\"body\":{\"body\":\"12345\"},\"fromUser\":\"admin\",\"toTarget\":\"user_1584422783691\",\"type\":\"TEXT\",\"way\":\"P2P\"}")},
    {"获取用户信息": ("userGet", "{\"auid\":\"admin\"}")},
    {"更新用户": ("userUpdate", "{\"auid\":\"user_1584422783691\",\"avatar\":\"http://www.baidu.com\",\"birth\":\"2020-12-31\",\"email\":\"aa@qq.com\",\"ex\":\"data\",\"gender\":0,\"mobile\":\"13800138000\",\"name\":\"张三\",\"sign\":\"张三的签名\"}")},
    {"用户列表": ("userList", "{\"auids\":[\"admin\"]}")},
    {"更新用户Token": ("userUpdateToken", "{\"auid\":\"user_1584422783691\",\"token\":\"123456\"}")},
    {"刷新用户Token": ("userRefreshToken", "{\"auid\":\"user_1584422783691\"}")},
    {"获取用户历史信息": ("historyListMessage", "{\"endTimestamp\":1599702645000,\"fromUser\":\"admin\",\"limit\":10,\"startTimestamp\":0,\"toTarget\":\"user_1584422783691\",\"way\":\"P2P\"}")},
    {"获取用户历史会话": ("historyListSession", "{\"auid\":\"admin\",\"endTimestamp\":1599702645000,\"startTimestamp\":0}")},
    {"添加朋友": ("addFriend", "{\"alias\":\"好友A\",\"applyText\":\"直接添加好友，我是XXX\",\"auid\":\"admin\",\"targetAuid\":\"user_1584422783691\",\"type\":\"ADD\"}")},
    {"删除朋友": ("delFriend", "{\"auid\":\"admin\",\"targetAuid\":\"user_1584422783691\"}")},
    {"获取朋友列表": ("listFriends", "{\"auid\":\"admin\",\"updatetime\":0}")},
    {"获取好友": ("getFriend", "{\"auid\":\"admin\",\"targetAuid\":\"user_1584422783691\"}")},
    {"修改朋友黑名单/禁言": ("modifyBlacklistForbid", "{\"auid\":\"admin\",\"targetAuid\":\"user_1584422783691\",\"type\":\"ADD_BLACKLIST\"}")},
    {"获取朋友黑名单/禁言列表": ("listBlackListForbid", "{\"auid\":\"admin\"}")},
    {"修改朋友别名": ("modifyAlias", "{\"alias\":\"昵称X\",\"auid\":\"admin\",\"targetAuid\":\"user_1584422783691\"}")},
    {"添加群": ("addRoom", "{\"announce\":\"公告\",\"avatar\":\"http://www.baidu.com\",\"confBeinvite\":\"\",\"confInviteother\":\"\",\"confJoinmode\":\"\",\"confUpdate\":\"\",\"introduce\":\"群的简介\",\"inviteText\":\"邀请文字\",\"maxMember\":100,\"members\":[\"user_1584422783691\"],\"name\":\"ui新建的群\",\"owner\":\"admin\"}")},
    {"更新群": ("updateRoom", "{\"announce\":\"公告\",\"avatar\":\"http://www.baidu.com\",\"confBeinvite\":\"\",\"confInviteother\":\"\",\"confJoinmode\":\"\",\"confUpdate\":\"\",\"introduce\":\"简介\",\"maxMember\":100,\"name\":\"ui新建的群\",\"owner\":\"admin\",\"rid\":22}")},
    {"获取群列表": ("listRoom", "{\"rids\":[22]}")},
    {"获取用户加入的群": ("listRoomJoin", "{\"auid\":\"admin\"}")},
    {"删除群": ("delRoom", "{\"owner\":\"admin\",\"rid\":22}")},
    {"获取单个群信息": ("getRoom", "{\"rid\":22}")},
    {"列出群成员": ("listRoomMember", "{\"rids\":[22]}")},
    {"添加群成员": ("addRoomMember", "{\"ex\":\"附加参数\",\"inviteText\":\"邀请你进群\",\"members\":[\"admin_1585295718288\"],\"needAgree\":0,\"owner\":\"admin\",\"rid\":22}")},
    {"删除群成员": ("delRoomMember", "{\"ex\":\"踢出群附加信息\",\"members\":[\"admin_1585295718288\"],\"owner\":\"admin\",\"rid\":22}")},
    {"列出用户的在线状态": ("userOnline", "{\"auids\":[\"admin\"]}")},
]




class DialogController(QObject):
    signalSdkInit = pyqtSignal(str)
    signalSdkListener = pyqtSignal(str)
    signalApiListener = pyqtSignal(str)
    signalUploadListener = pyqtSignal(str)

    def __init__(self, parent=None):
        super(DialogController, self).__init__(parent)

    def init(self, dllPath):
        self.valueSelected = ()
        self.dllPath = dllPath
        self.view = None
        self.uploadFilePath = ""

    def onSdkInit(self, ret, err_msg):
        self.signalSdkInit.emit("sdk init ret:{}, reason = {}".format(ret, err_msg.decode("utf8")))

    def onSignalSdkInit(self, msg):
        self.view.msgContentTextEdit.append(msg)

    def onSdkListener(self, method, argc, argv):
        self.signalSdkListener.emit(
            "sdkListenerCallback: method = {}, argv[0]={}".format(method.decode("utf8"), argv[0].decode("utf8")))

    def onSignalSdkListener(self, msg):
        self.view.msgContentTextEdit.append(msg)


    def connectSdk(self):
        configJson = self.view.sdkConfigTextEdit.toPlainText()
        result = echatimSdk.sdkInit(self.dllPath, configJson, self.onSdkInit, self.onSdkListener)
        if result:
            # 初始化文件上传接口
            echatimSdk.sdkFileServerInit(uploadCb=self.onFileServerUploadListener)

            self.view.connectButton.setEnabled(False)
            self.view.sendButton.setEnabled(True)
            self.view.fileButton.setEnabled(True)
            self.view.uploadButton.setEnabled(True)
            pass


    def onConnect(self):
        t = Thread(target=self.connectSdk)
        t.start()

    def onApisReturnContent(self, content):
        # print("===> sdk api return:{} ".format(content))
        self.signalSdkListener.emit(content)

    def onSignalApisReturnContent(self, msg):
        self.view.msgContentTextEdit.append(msg)

    def onApiSelectorSelected(self, index):
        valueSelected = self.view.apiSelector.itemData(index)
        if not valueSelected or len(valueSelected) == 0:
            return

        self.view.apiFormTextEdit.setPlainText(valueSelected[1])
        self.valueSelected = valueSelected

    def onSendApi(self):
        valueSelected = self.valueSelected
        if len(valueSelected) == 0:
            print("not select any api")
            return

        method = valueSelected[0]
        postJson = self.view.apiFormTextEdit.toPlainText()
        # 调用测试API
        echatimSdk.apiCall(method, postJson, self.onApisReturnContent)

    def onFileSelected(self):
        result = QtWidgets.QFileDialog.getOpenFileName(None, "getOpenFileName", "./",
                                                       "All Files (*);;Text Files (*.txt)")
        if not result[0]:
            return

        self.uploadFilePath = result[0]
        # QT的文件选择器, 在Windows平台下的文件路径分割符返回的是'/', 将其替换成'\'
        if platform.system()== 'Windows':
            self.uploadFilePath = self.uploadFilePath.replace("/", "\\")
        self.view.filePathTextEdit.setPlainText(self.uploadFilePath)
        print("===> select file:{} ".format(self.uploadFilePath))


    # 回调监听器
    def onFileServerUploadListener(self, method, argv0, argv1):
        self.signalSdkInit.emit(" onFileServerUploadListener, method: {}, argv0 = {}, argv1 = {}".format(method, argv0, argv1))
        pass

    def onSignalUploadListener(self, msg):
        self.view.msgContentTextEdit.append(msg)



    def onFileUpload(self):
        self.uploadFilePath = self.view.filePathTextEdit.toPlainText()
        print("===> ready upload file:{} ".format(self.uploadFilePath))
        echatimSdk.sdkFileServerUpload(self.uploadFilePath)
        pass




    def onCreate(self):
        _translate = QtCore.QCoreApplication.translate
        app = QtWidgets.QApplication(sys.argv)
        MainDialog = QtWidgets.QDialog()
        view = Ui_Dialog()
        view.setupUi(MainDialog)
        self.view = view


        i = 1
        for item in TEST_APIS_DICT:
            key = list(item.keys())[0]
            value = list(item.values())[0]
            self.view.apiSelector.addItem(key, value)
            self.view.apiSelector.setItemText(i, _translate("Dialog", key))
            i = i + 1

        # view.fileButton.clicked.connect(lambda: print(QtWidgets.QFileDialog.getOpenFileName(None,"getOpenFileName","./","All Files (*);;Text Files (*.txt)")))
        view.connectButton.clicked.connect(self.onConnect)
        view.sendButton.clicked.connect(self.onSendApi)
        view.fileButton.clicked.connect(self.onFileSelected)
        view.uploadButton.clicked.connect(self.onFileUpload)
        view.clearButton.clicked.connect(self.view.msgContentTextEdit.clear)
        view.apiSelector.currentIndexChanged.connect(self.onApiSelectorSelected)

        self.view.sendButton.setEnabled(False)
        self.view.fileButton.setEnabled(False)
        self.view.uploadButton.setEnabled(False)

        # 消息信号
        self.signalSdkInit.connect(self.onSignalSdkInit)
        self.signalSdkListener.connect(self.onSignalSdkInit)
        self.signalApiListener.connect(self.onSignalApisReturnContent)
        self.signalUploadListener.connect(self.onSignalUploadListener)

        MainDialog.show()
        sys.exit(app.exec_())

        pass
